﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Web.Ajax.Data
{
	public class Predicate
	{
		public static Predicate<T> And<T>(params Predicate<T>[] pl)
		{			
			if (pl == null || pl.Length == 0)
				return d=>true;

			return d =>
			{
				var b = true;
				foreach (var p in pl)
				{
					b = b && p(d);
					if (!b)
						return b;
				}
				return b;
			};			
		}

		public static Predicate<T> Or<T>(params Predicate<T>[] pl)
		{
			if (pl == null || pl.Length == 0)
				return d => true;

			return d=>
			{
				var b = false;
				foreach (var p in pl)
				{
					b = b || p(d);
					if (b)
						return b;
				}
				return b;
			};			
		}

		public static Predicate<T> Not<T>(params Predicate<T>[] pl)
		{
			if (pl == null || pl.Length == 0)
				return d => true;

			return d =>
			{
				if (pl!=null && pl.Length == 1)
					return !(pl[0](d));
				else
					return !(And<T>(pl))(d);
			};			
		}
	}
}